package cn.satoken.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.satoken.entity.CrmCustomer;
import cn.satoken.entity.SysUser;
import cn.satoken.mapper.CustomerMapper;
import cn.satoken.mapper.SysUserMapper;
import cn.satoken.service.CustomerService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * <h3>saToken</h3>
 * <p></p>
 *
 * @author gdw
 * @since 2025-06-05 09:45:07
 */
@Service
@Transactional
@RequiredArgsConstructor
public class CustomerServcieImpl extends ServiceImpl<CustomerMapper, CrmCustomer> implements CustomerService {
    private final CustomerMapper customerMapper;
    private final SysUserMapper sysUserMapper;
    @Override
    public SaResult saveCustomer(CrmCustomer customer) {
        //获取当前用户
        Long userId = StpUtil.getLoginIdAsLong();
        customer.setCreateUserId(userId);
        return  customerMapper.insert(customer)>0?SaResult.ok("保存成功"):SaResult.error("保存失败");
    }

    @Override
    public SaResult updateCustomer(CrmCustomer customer) {
        return customerMapper.updateById(customer)>0?SaResult.ok("修改成功"):SaResult.error("修改失败");
    }

    @Override
    public SaResult selectPage(int page, int size, Map<String, Object> condition) {
        Page<CrmCustomer> page1=new Page<>(page,size);
        LambdaQueryWrapper<CrmCustomer> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.like(condition.get("name")!=null,CrmCustomer::getContactPerson,condition.get("name"))
                .eq(condition.get("source")!=null,CrmCustomer::getSource,condition.get("source"))
                .between(condition.get("startTime")!=null,CrmCustomer::getNextFollowTime,condition.get("startTime"),condition.get("endTime"));
        Page<CrmCustomer> crmCustomerPage = customerMapper.selectPage(page1, queryWrapper);
        crmCustomerPage.getRecords().forEach(customer->{
            SysUser sysUser = sysUserMapper.selectById(customer.getFollowUserId());
            customer.setFollowName(sysUser.getName());
        });
        return SaResult.data(crmCustomerPage);
    }
}
